<template>
  <el-card class="search-card">
    <el-form :model="searchForm" label-width="80px" inline>
      <el-form-item label="工单编号">
        <el-input v-model="searchForm.productionOrderCode" placeholder="工单编号" clearable />
      </el-form-item>
      <el-form-item label="工单名称">
        <el-input v-model="searchForm.productionOrderName" placeholder="工单名称" clearable />
      </el-form-item>
      <el-form-item label="单据来源">
        <el-select style="width: 120px" clearable v-model="searchForm.productionOrderSource" placeholder="单据来源">
          <el-option label="客户订单" :value="1"/>
          <el-option label="库存备货" :value="2"/>
        </el-select>
      </el-form-item>
      <el-form-item label="物料编号">
        <el-input v-model="searchForm.material.code" placeholder="物料编号" clearable />
      </el-form-item>
      <el-form-item label="物料名称">
        <el-input v-model="searchForm.material.name" placeholder="物料名称" clearable />
      </el-form-item>
      <el-form-item label="客户编号">
        <el-input v-model="searchForm.customer.code" placeholder="客户编号" clearable />
      </el-form-item>
      <el-form-item label="客户名称">
        <el-input v-model="searchForm.customer.name" placeholder="客户名称" clearable />
      </el-form-item>
      <el-form-item label="工单类型">
        <el-select style="width: 120px" clearable v-model="searchForm.productionOrderType" placeholder="单据来源">
          <el-option
              v-for="dictData in productionOrderTypeDictDataList"
              :value="dictData.id"
              :label="dictData.dictLabel"
              :key="dictData.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态">
        <el-select style="width: 120px;" v-model="searchForm.status" placeholder="请选择状态" clearable>
          <el-option
              v-for="dictData in productionOrderStatusDictDataList"
              :label="dictData.dictLabel"
              :value="dictData.id"
              :key="dictData.id"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch" :icon="Search">搜索</el-button>
        <el-button @click="resetSearch" :icon="Refresh">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>

  <div class="toolbar">
    <el-button type="primary" @click="handleAdd" :icon="Plus">新增工单</el-button>
    <el-button type="danger" @click="handleBatchDelete" :icon="Delete" :disabled="selectedRows.length === 0">批量删除</el-button>
  </div>
  
  <el-card class="table-card">
    <el-table :data="productionOrderList" border stripe @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column prop="productionOrderCode" label="工单编号" />
      <el-table-column prop="productionOrderName" label="工单名称" />
      <el-table-column prop="typeDictData.dictLabel" label="工单类型" />
      <el-table-column prop="productionOrderSource" label="工单来源">
        <template #default="scope">
          {{scope.row.productionOrderSource == 1?'客户订单':'库存备货'}}
        </template>
      </el-table-column>
      <el-table-column prop="orderCode" label="订单编号" />
      <el-table-column prop="material.code" label="产品/物料编号" />
      <el-table-column prop="material.name" label="产品/物料名称" />
      <el-table-column prop="material.specification" label="规格" />
      <el-table-column prop="material.unit.name" label="单位" />
      <el-table-column prop="productionOrderQuantity" label="工单数量" />
      <el-table-column prop="customer.code" label="客户编号" />
      <el-table-column prop="customer.name" label="客户名称" />
      <el-table-column prop="requestDate" label="需求日期" />
      <el-table-column prop="status" label="状态">
        <template #default="scope">
          {{ formatStatus(scope.row.status) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="scope">
          <template v-if="scope.row.status === 30">
          <el-button size="small" @click="handleEdit(scope.row)" :icon="Edit">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.row)" :icon="Delete">删除</el-button>
          </template>
          <el-button size="small" @click="openAdjustReviewApproved(scope.row)" v-if="scope.row.status == 31 " :icon="Check">审核</el-button>
          <!-- <el-button size="small" @click="handleReviewConfirm(scope.row)" v-if="scope.row.id ===reviewTargetId" :icon="Check">审核</el-button> -->
          <el-button size="small" v-if="scope.row.status !== 30" :icon="MessageBox">预览</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-card>

  <div class="pagination-container">
    <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />
  </div>

  <el-dialog
      :title="dialogTitle"
      v-model="addOrUpdateDialogVisable"
      width="80%"
      :close-on-click-modal="false">
      <el-form :model="productionOrderForm" label-width="100px">
      <el-row :gutter="20">
        <el-col :span="16">
          <el-row>
            <el-col :span="12">
              <el-form-item label="工单编号" required>
                <el-input v-model="productionOrderForm.productionOrderCode" placeholder="请输入工单编号"/>
                <el-switch
                    @click="autoCode"
                    v-model="isAutoCode"
                    inline-prompt
                    active-text="自动生成"
                    inactive-text="手动输入"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="工单名称" required>
                <el-input v-model="productionOrderForm.productionOrderName" placeholder="请输入工单名称"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="来源类型" required>
                <el-radio-group v-model="productionOrderForm.productionOrderSource">
                  <el-radio :label="1">客户订单</el-radio>
                  <el-radio :label="2">库存备货</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="工单类型" required>
                <el-select v-model="productionOrderForm.productionOrderType" placeholder="请选择工单类型">
                  <el-option
                      v-for="dict in productionOrderTypeDictDataList"
                      :key="dict.id"
                      :label="dict.dictLabel"
                      :value="dict.id"/>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row v-if="productionOrderForm.productionOrderSource === 1">
            <el-col :span="12">
              <el-form-item label="客户编号" required>
                <el-input v-model="productionOrderForm.customerCode" placeholder="请选择客户">
                  <template #append>
                    <el-button @click="openCustomerSelectDialog" :icon="Search" />
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="客户名称">
                <el-input v-model="productionOrderForm.customerName" placeholder="选择客户后自动带出" disabled/>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="产品编号" required>
                <el-input v-model="productionOrderForm.materialCode" placeholder="请选择产品">
                  <template #append>
                    <el-button @click="openProductSelectDialog" :icon="Search" />
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="产品名称" required>
                <el-input v-model="productionOrderForm.materialName" placeholder="选择产品后自动带出" disabled/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="规格型号">
                <el-input v-model="productionOrderForm.specification" placeholder="选择产品后自动带出" disabled/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="单位">
                <el-input v-model="productionOrderForm.unitName" placeholder="选择产品后自动带出" disabled/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="工单数量" required>
                <el-input-number v-model="productionOrderForm.productionOrderQuantity" :min="1" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="需求日期" required>
                <el-date-picker
                    v-model="productionOrderForm.requestDate"
                    type="date"
                    placeholder="请选择需求日期"
                    value-format="YYYY-MM-DD"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="状态" required>
                <el-select v-model="productionOrderForm.status" placeholder="请选择初始状态">
                   <el-option
                      v-for="dict in productionOrderStatusDictDataList"
                      :key="dict.id"
                      :label="dict.dictLabel"
                      :value="dict.id"/>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="备注">
            <el-input v-model="productionOrderForm.remark" :rows="3" type="textarea" placeholder="请输入备注"/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="工单二维码">
            <el-upload
                class="avatar-uploader"
                action="#" 
                :show-file-list="false"
                :http-request="() => {}">
              <img v-if="productionOrderForm.qrCodeUrl" :src="productionOrderForm.qrCodeUrl" class="avatar" alt=""/>
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-card v-if="isEdit">
      <el-tabs type="border-card">
        <el-tab-pane label="BOM组成">
          <MaterialBom :parentMaterialId="productionOrderForm.materialId">
          </MaterialBom>
        </el-tab-pane>
        <el-tab-pane label="物料需求">
          
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancelAddOrUpdate">关闭</el-button>
        <el-button v-if="isEdit" @click="markRowFowReview">确认</el-button>
        <el-button v-if="!isDetail" type="primary" @click="submitProductionOrderForm">保存</el-button>
      </span>
    </template>
  </el-dialog>

  <el-dialog title="选择产品物料" v-model="productSelectDialogVisible" width="70%" append-to-body>
    <el-form :model="productSearchParams" label-width="100px" inline>
       <el-form-item label="物料产品编码">
         <el-input v-model="productSearchParams.code" placeholder="物料产品编码" clearable/>
       </el-form-item>
       <el-form-item label="物料产品名称">
         <el-input v-model="productSearchParams.name" placeholder="物料产品名称" clearable/>
       </el-form-item>
       <el-form-item>
         <el-button type="primary" @click="searchProducts" :icon="Search">搜索</el-button>
       </el-form-item>
    </el-form>
    <el-table :data="productList" border stripe>
      <el-table-column width="55" align="center">
        <template #header>选择</template>
        <template #default="scope">
          <el-radio :label="scope.row.id" v-model="tempSelectedProductId" @change="handleTempProductSelect(scope.row)">
            &nbsp;
          </el-radio>
        </template>
      </el-table-column>
      <el-table-column prop="code" label="产品物料编码" />
      <el-table-column prop="name" label="产品物料名称" />
      <el-table-column prop="specification" label="规格型号" />
      <el-table-column prop="unit.name" label="单位" />
      <el-table-column prop="category.name" label="分类" />
    </el-table>
     <el-pagination
        class="dialog-pagination"
        v-model:current-page="productPagination.currentPage"
        v-model:page-size="productPagination.pageSize"
        :page-sizes="[5, 10, 20, 50]"
        :total="productPagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleProductPageSizeChange"
        @current-change="handleProductCurrentChange"
    />
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="productSelectDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmProductSelection">确定</el-button>
      </span>
    </template>
  </el-dialog>

  <el-dialog title="选择客户" v-model="customerSelectDialogVisible" width="70%" append-to-body>
    <el-form :model="customerSearchParams" label-width="80px" inline>
       <el-form-item label="客户编码">
         <el-input v-model="customerSearchParams.code" placeholder="客户编码" clearable/>
       </el-form-item>
       <el-form-item label="客户名称">
         <el-input v-model="customerSearchParams.name" placeholder="客户名称" clearable/>
       </el-form-item>
       <el-form-item>
         <el-button type="primary" @click="searchCustomers" :icon="Search">搜索</el-button>
       </el-form-item>
    </el-form>
    <el-table :data="customerList" border stripe>
      <el-table-column width="55" align="center">
        <template #header>选择</template>
        <template #default="scope">
          <el-radio :label="scope.row.id" v-model="tempSelectedCustomerId" @change="handleTempCustomerSelect(scope.row)">
            &nbsp;
          </el-radio>
        </template>
      </el-table-column>
      <el-table-column prop="code" label="客户编码" />
      <el-table-column prop="name" label="客户名称" />
      <el-table-column prop="contactPerson" label="联系人" />
      <el-table-column prop="phone" label="联系电话" />
    </el-table>
     <el-pagination
        class="dialog-pagination"
        v-model:current-page="customerPagination.currentPage"
        v-model:page-size="customerPagination.pageSize"
        :page-sizes="[5, 10, 20, 50]"
        :total="customerPagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleCustomerPageSizeChange"
        @current-change="handleCustomerCurrentChange"
    />
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="customerSelectDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmCustomerSelection">确定</el-button>
      </span>
    </template>
  </el-dialog>
  <!-- 审核的通过与否 -->
   <el-dialog title="审核确认" v-model="isAdjustReviewApproved" width="30%" center>
    <div style="text-align: center;">
      <span>确定通过审核嘛</span>
    </div>
    <template #footer>
      <el-button @click="handleReview(false)">不通过</el-button>
      <el-button type="primary" @click="handleReview(true)">通过</el-button>
    </template>
   </el-dialog>
</template>

<script setup>
// =================================================================================================
// 模块一：导入工具 (Imports)
// -------------------------------------------------------------------------------------------------
// 核心工具：从 vue 中导入 ref(创建响应式变量) 和 onMounted(生命周期钩子)
import { ref, onMounted } from "vue";
// UI组件：从 element-plus 导入图标、消息提示和确认对话框
import { Plus, Search, Refresh, Edit, Delete, MessageBox, Check } from '@element-plus/icons-vue'
import { ElButton, ElMessage, ElMessageBox } from "element-plus";
// API函数：从我们自己写的 api 文件中，导入所有和后端交互的函数
import {
  getProductionOrderList, getAutoCode, addProductionOrder,
  updateProductionOrder, deleteProductionOrder, batchDeleteProductionOrder
} from "@/api/production-order.js";
import { getDictDataList } from "@/api/dictData.js";
import { getMaterialPage } from "@/api/material.js";
import { getCustomerPage } from "@/api/customer.js";
import MaterialBom from "./materialBom.vue";


// =================================================================================================
// 模块二：属性声明 (State / Reactive Variables)
// -------------------------------------------------------------------------------------------------
// 这一部分负责定义页面需要“记住”的所有数据和状态

// --- 主页面与查询相关 ---
const getInitialSearchForm = () => ({
  productionOrderCode:"", productionOrderName:"",
  material:{code:"",name:""}, status:"", productionOrderSource:"",
  customer:{code:"",name:""}, productionOrderType:"",
});
const searchForm = ref(getInitialSearchForm()); // 搜索表单的数据
const productionOrderList = ref([])             // 主表格的数据
const pagination = ref({ currentPage:1, pageSize:10, total:0 }) // 主表格的分页数据
const selectedRows = ref([]);                   // 主表格中被复选框选中的行

// --- 新增/编辑弹窗相关 ---
const dialogTitle = ref("新增工单");
const addOrUpdateDialogVisable = ref(false); // 控制弹窗的显示和隐藏
const isEdit = ref(false);                     // 标记当前是新增模式还是编辑模式
const reviewTargetId = ref(null);           //存入当前进入审核状态的id
const getInitialFormData = () => ({
  id: null, productionOrderCode: "", productionOrderName: "",
  productionOrderSource: 1, productionOrderType: null,
  materialId: null, materialCode: "", materialName: "",
  specification: "", unitName: "",
  productionOrderQuantity: 1, requestDate: "",
  status: 10, remark: "", qrCodeUrl: "",
  customerId: null, customerCode: '', customerName: ''
});
const productionOrderForm = ref(getInitialFormData()); // 新增/编辑表单的数据
const isAutoCode = ref(false);
const isDetail = ref(false);

// --- 字典数据 ---
const productionOrderTypeDictDataList = ref([]);   // 工单类型字典
const productionOrderStatusDictDataList = ref([]); // 工单状态字典

// --- 产品选择弹窗相关 ---
const productSelectDialogVisible = ref(false);
const productList = ref([]);
const productSearchParams = ref({ code: '', name: '' });
const productPagination = ref({ currentPage: 1, pageSize: 10, total: 0 });
const tempSelectedProductId = ref(null);
const tempSelectedProduct = ref(null);

// --- 客户选择弹窗相关 ---
const customerSelectDialogVisible = ref(false);
const customerList = ref([]);
const customerSearchParams = ref({ code: '', name: '' });
const customerPagination = ref({ currentPage: 1, pageSize: 10, total: 0 });
const tempSelectedCustomerId = ref(null);
const tempSelectedCustomer = ref(null);

//工单编辑相关
const   isAdjustReviewApproved = ref(false);//审核弹窗的开关
const currentReview = ref(null);//记录当前正在审核的行

// =================================================================================================
// 模块三：核心业务函数 (CRUD - 增删改查)
// -------------------------------------------------------------------------------------------------
// 这一部分是页面的主要逻辑，负责处理增、删、改、查等核心操作

// --- 查询 (Read) ---
const handleSearch = () => {
  const params = {
    pageNum: pagination.value.currentPage, pageSize: pagination.value.pageSize,
    productionOrderCode: searchForm.value.productionOrderCode,
    productionOrderName: searchForm.value.productionOrderName,
    productionOrderSource: searchForm.value.productionOrderSource,
    productionOrderType: searchForm.value.productionOrderType,
    status: searchForm.value.status,
    materialCode: searchForm.value.material.code,
    materialName: searchForm.value.material.name,
    customerCode: searchForm.value.customer.code,
  };
  getProductionOrderList(params).then(res => {
    productionOrderList.value = res.data.list;
    pagination.value.total = res.data.total;  
  }).catch(err => {
    ElMessage.error('获取工单列表失败');
    productionOrderList.value = []; pagination.value.total = 0; console.error(err);
  });
}

// --- 新增 (Create) ---
const handleAdd = ()=>{
  resetForm();
  isEdit.value = false;
  dialogTitle.value = "新增工单";
  addOrUpdateDialogVisable.value = true;
}

// --- 修改 (Update) ---
const handleEdit = (row) => {
  resetForm();
  isEdit.value = true;
  dialogTitle.value = "编辑工单";
  Object.assign(productionOrderForm.value, {
    ...row,
    materialId: row.material?.id,
    materialCode: row.material?.code,
    materialName: row.material?.name,
    specification: row.material?.specification,
    unitName: row.material?.unit?.name,
    customerId: row.customer?.id,
    customerCode: row.customer?.code,
    customerName: row.customer?.name,
  });
  addOrUpdateDialogVisable.value = true;
}


// --- 提交新增或修改的表单 ---
const submitProductionOrderForm = ()=>{
  const payload = { ...productionOrderForm.value };
  if (payload.productionOrderSource !== 1) {
    payload.customerId = null;
    payload.customerCode = null;
  }
  const apiCall = isEdit.value ? updateProductionOrder(payload) : addProductionOrder(payload);
  const successMsg = isEdit.value ? '工单更新成功！' : '工单新增成功！';
  apiCall.then(res => {
    if(res.code === 200){
      ElMessage.success(successMsg);
      addOrUpdateDialogVisable.value = false;
      handleSearch();
    } else { ElMessage.error(res.msg || '操作失败'); }
  }).catch(err => { ElMessage.error('请求失败'); console.error(err); });
}

// --- 删除 (Delete) ---
const handleDelete = (row) => {
  ElMessageBox.confirm(`确定删除工单 "${row.productionOrderName}" 吗？`, '警告', { type: 'warning' })
  .then(() => {
    deleteProductionOrder(row.id).then(res => {
      if(res.code === 200) { ElMessage.success('删除成功！'); handleSearch(); }
      else { ElMessage.error(res.msg || '删除失败'); }
    })
  }).catch(() => { ElMessage.info('已取消删除'); });
}

// --- 批量删除 (Batch Delete) ---
const handleBatchDelete = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请至少选择一条数据！');
    return;
  }
  ElMessageBox.confirm(`确定删除选中的 ${selectedRows.value.length} 条工单吗？`, '警告', { type: 'warning' })
  .then(() => {
    const ids = selectedRows.value.map(item => item.id);
    batchDeleteProductionOrder(ids).then(res => {
       if(res.code === 200) { ElMessage.success('批量删除成功！'); handleSearch(); }
       else { ElMessage.error(res.msg || '批量删除失败'); }
    })
  }).catch(() => { ElMessage.info('已取消删除'); });
}

//审核功能
const handleReview = (isApproved) =>{
  const originalOrder = currentReview.value;
  if (!originalOrder) {
    ElMessage.error('无法找到要审核的工单信息！');
    return;
  }

  const newStatus = isApproved ?32:30;

     const payload = {
    ...originalOrder,      // 包含原始工单的所有信息
    status: newStatus      // 只覆盖 status 字段
  };
    isAdjustReviewApproved.value = false;
    updateProductionOrder(payload).then(res =>{
      if(res.code === 200){
        ElMessage.success(isApproved?'审核通过':'审核不通过打回草稿');
        handleSearch();
      }
      else{
        ElMessage.error(res.msg || '审核失败');
      }
    }).catch(err => {
    console.error("请求失败，请检查网络或后端服务", err);
    ElMessage.error(`操作失败了，原因可能是：${err.msg || err.message || '未知错误'}`);
});
}

// =================================================================================================
// 模块四：页面辅助函数 (Helpers & Utilities)
// -------------------------------------------------------------------------------------------------
// 这部分函数不直接处理增删改查，但为页面提供支持，如翻页、重置、格式化等

// --- 主页面辅助 ---
const handleSizeChange =(pageSize)=>{
  pagination.value.pageSize = pageSize;
  handleSearch();
}
const handleCurrentChange =(newPage)=>{
  pagination.value.currentPage = newPage;
  handleSearch();
}
const resetSearch = () => {
  searchForm.value = getInitialSearchForm();
  handleSearch();
}
const handleSelectionChange = (selection) => {
  selectedRows.value = selection;
}
const formatStatus = (statusId) => {
  const status = productionOrderStatusDictDataList.value.find(item => item.id === statusId);
  return status ? status.dictLabel : '未知状态';
};

// --- 新增/编辑弹窗辅助 ---
const cancelAddOrUpdate = ()=>{
  addOrUpdateDialogVisable.value = false;
}
//标记哪一行需要审核
const markRowFowReview=()=>{
  reviewTargetId.value  = productionOrderForm.value.id;
  productionOrderForm.value.status = 31;
  updateProductionOrder(productionOrderForm.value).then(res =>{
    if(res.code === 200){
      ElMessage.success("确认成功");
      addOrUpdateDialogVisable.value = false;
      handleSearch();
    }
  })
  
}
const handleReviewConfirm=(row)=>{
  updateProductionOrder({...row,status: 32}).then(res => {
    
        // 第3步：根据结果进行后续操作
        // 助理办完事回来了，递上办理结果报告(res)。
        // 经理先看一眼报告上的结果戳，是不是 code === 200 (代表“办理成功”)。
        if(res.code === 200) {
        
            // a. 广播通知
            // 事情办妥了，经理很满意，就在办公室广播里宣布：“审核确认成功！”
            // (页面上弹出一个绿色的成功提示)
            ElMessage.success('审核确认成功！');
            
            // b. 清理桌面
            // 还记得我们用来标记“哪一行需要审核”的那个小记事本 reviewTargetId 吗？
            // 这件事办完了，经理就把记事本上那条记录划掉 (设置为 null)，表示这个任务已结束。
            // (这样，表格上那个【审核】按钮因为找不到对应的ID，就自动消失了)
            reviewTargetId.value = null; 
            
            // c. 更新看板
            // 最后，为了确保墙上的总览看板信息最新，经理让助理再去把所有文件的最新列表拿过来刷新一遍。
            // (重新调用 handleSearch() 来刷新整个表格，显示出最新的数据)
            handleSearch();
        }
    });

}
const openAdjustReviewApproved=(row)=>{
  currentReview.value = row;
  isAdjustReviewApproved.value = true;
}

//自动生成code
const autoCode = ()=>{
  getAutoCode().then(res => {
    productionOrderForm.value.productionOrderCode = res.data;
  })
}
const resetForm = () => {
  productionOrderForm.value = getInitialFormData();
}

// --- 加载字典 ---
const loadProductionOrderStatusDictDataList=()=>{
  getDictDataList({dictType:"PRODUCTION_ORDER_STATUS"}).then(res=>{
    productionOrderStatusDictDataList.value = res.data.records;
  })
}
const loadProductOrderDictDataList=()=>{
  getDictDataList({dictType:"PRODUCTION_ORDER_TYPE"}).then(res=>{
    productionOrderTypeDictDataList.value = res.data.records;
  })
}


// =================================================================================================
// 模块五：辅助弹窗函数 (Sub-Dialog Functions)
// -------------------------------------------------------------------------------------------------
// 这部分专门处理“选择产品”、“选择客户”等子弹窗的逻辑

// --- 产品选择功能 ---
const openProductSelectDialog = () => {
  tempSelectedProductId.value = null; tempSelectedProduct.value = null;
  productSearchParams.value = { code: '', name: '' };
  productPagination.value.currentPage = 1;
  productSelectDialogVisible.value = true;
  searchProducts();
}
const searchProducts = () => {
  getMaterialPage(productPagination.value.currentPage, productPagination.value.pageSize, productSearchParams.value)
  .then(res => {
    productList.value = res.data.list;
    productPagination.value.total = res.data.total;
  }).catch(err => { ElMessage.error('获取产品列表失败'); console.error(err); })
}
const handleProductPageSizeChange = (pageSize) => {
  productPagination.value.pageSize = pageSize; searchProducts();
}
const handleProductCurrentChange = (newPage) => {
  productPagination.value.currentPage = newPage; searchProducts();
}
const handleTempProductSelect = (selectedRow) => {
  tempSelectedProduct.value = selectedRow;
}
const confirmProductSelection = () => {
  if (!tempSelectedProduct.value) { ElMessage.warning('请先选择一个产品物料！'); return; }
  const selected = tempSelectedProduct.value;
  productionOrderForm.value.materialId = selected.id;
  productionOrderForm.value.materialCode = selected.code;
  productionOrderForm.value.materialName = selected.name;
  productionOrderForm.value.specification = selected.specification;
  productionOrderForm.value.unitName = selected.unit ? selected.unit.name : '';
  productSelectDialogVisible.value = false;
}

// --- 客户选择功能 ---
const openCustomerSelectDialog = () => {
  tempSelectedCustomerId.value = null; tempSelectedCustomer.value = null;
  customerSearchParams.value = { code: '', name: '' };
  customerPagination.value.currentPage = 1;
  customerSelectDialogVisible.value = true;
  searchCustomers();
}
const searchCustomers = () => {
  getCustomerPage(customerPagination.value.currentPage, customerPagination.value.pageSize, customerSearchParams.value)
  .then(res => {
    customerList.value = res.data.list;
    customerPagination.value.total = res.data.total;
  }).catch(err => { ElMessage.error('获取客户列表失败'); console.error(err); })
}
const handleCustomerPageSizeChange = (pageSize) => {
  customerPagination.value.pageSize = pageSize; searchCustomers();
}
const handleCustomerCurrentChange = (newPage) => {
  customerPagination.value.currentPage = newPage; searchCustomers();
}
const handleTempCustomerSelect = (selectedRow) => {
  tempSelectedCustomer.value = selectedRow;
}
const confirmCustomerSelection = () => {
  if (!tempSelectedCustomer.value) { ElMessage.warning('请先选择一个客户！'); return; }
  const selected = tempSelectedCustomer.value;
  productionOrderForm.value.customerId = selected.id;
  productionOrderForm.value.customerCode = selected.code;
  productionOrderForm.value.customerName = selected.name;
  customerSelectDialogVisible.value = false;
}


// =================================================================================================
// 模块六：生命周期钩子 (Lifecycle Hooks)
// -------------------------------------------------------------------------------------------------
// 这部分代码会在组件生命周期的特定时刻自动执行

onMounted(()=>{
  // 当组件第一次加载到页面上时，自动执行以下操作：
  loadProductionOrderStatusDictDataList(); // 加载状态字典
  loadProductOrderDictDataList();      // 加载类型字典
  handleSearch();                      // 加载主表格第一页数据
})
</script>

<style scoped>
.dialog-pagination {
  margin-top: 15px;
  justify-content: flex-end;
}
.customer-container {
  padding: 20px;
}
.breadcrumb {
  margin-bottom: 20px;
}
.search-card {
  margin-bottom: 20px;
}
.toolbar {
  margin-bottom: 20px;
}
.table-card {
  margin-bottom: 20px;
}
.pagination-container {
  display: flex;
  justify-content: flex-end;
}
.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}
.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}
.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>